import { useCallback, useEffect } from "react"
import { useThemeConf } from "../stores/themeConf"

const useThemeWatch = () => {
  const {themeState, changeTheme} = useThemeConf()
  const themeListenHandler = useCallback(
    (e: MediaQueryListEvent) => {
      changeTheme('system');
    },
    [themeState]
  );
  useEffect(() => {
    changeTheme(themeState);
    if (themeState !== "system") {
      return;
    }
    const colorSchema = window.matchMedia("(prefers-color-scheme: dark)");
    colorSchema.addEventListener("change", themeListenHandler);

    return () => colorSchema.removeEventListener("change", themeListenHandler);
  }, [themeState])
}

export default useThemeWatch;